package com.test.service.impl;

import org.bson.Document;
import org.bson.types.ObjectId;
import org.springframework.beans.factory.annotation.Autowired;

import com.alibaba.dubbo.config.annotation.Service;
import com.test.constants.ErrorCode;
import com.test.dao.AccountDao;
import com.test.dto.account.FindPasswordDto;
import com.test.dto.account.LoginDto;
import com.test.dto.account.LogoutDto;
import com.test.dto.account.RegisterDto;
import com.test.dto.account.ResetPasswordDto;
import com.test.dto.base.BaseDto;
import com.test.service.AccountService;
import com.test.service.base.BaseService;
import com.test.utils.EncryptUtil;

@Service
public class AccountServiceImpl extends BaseService implements AccountService {
	@Autowired
	private AccountDao accountDao;
	
	@Override
	public BaseDto login(LoginDto loginDto) {
		Document user = accountDao.findUserByUsername(loginDto.getUsername());
		if(user == null){
			return getResult(ErrorCode.ACCOUNT_USER_NOT_FOUND);
		}
		if(!loginDto.getPassword().equals(user.getString("password"))) {
			return getResult(ErrorCode.ACCOUNT_INCORRECT_PASSWORD);
		}
		String username = user.getString("username");
		long timestamp = System.currentTimeMillis();
		String token = EncryptUtil.MD5(username + timestamp);
		//更新token
		accountDao.updateUserToken(user.getObjectId("_id"), token);
		
		user.put("token", token);
		user.put("id", user.getObjectId("_id").toHexString());
		return getResult(user);
	}

	@Override
	public BaseDto logout(LogoutDto logoutDto) {
		return null;
	}

	@Override
	public BaseDto register(RegisterDto registerDto) {
		Document user = accountDao.findUserByUsername(registerDto.getUsername());
		if(user != null) {
			return getResult(ErrorCode.ACCOUNT_REGISTER_EXISTED);
		}
		accountDao.register(registerDto);
		return getResult();
	}

	@Override
	public BaseDto findPassword(FindPasswordDto findPasswordDto) {
		return null;
	}

	@Override
	public BaseDto resetPassword(ResetPasswordDto resetPasswordDto) {
		return null;
	}

}
